
import time


class _EnvObject:
    def __init__(self, value, attr='str'):
        self.value = value
        self.attr = attr

    def __str__(self):
        return str(self.getValue())

    def setValue(self, value):
        self.value = value

    def getValue(self):
        return self.value

    def getAttr(self):
        return self.attr


class _EnvTimeObject(_EnvObject):
    def __init__(self, value=None, attr='time', autorefresh=True):
        self.autorefresh = autorefresh

        _EnvObject.__init__(self, value, attr)

    def __str__(self):
        return time.strftime("%H:%M:%S", time.gmtime(self.getValue()))

    def getValue(self):
        if self.autorefresh:
            return time.time()
        else:
            return _EnvObject.getValue(self)


class _EnvDateObject(_EnvTimeObject):
    def __init__(self, value=None, autorefresh=True):
        _EnvTimeObject.__init__(self, value, 'date', autorefresh)

    def __str__(self):
        return time.ctime(self.getValue())


class Environment:
    def __init__(self):
        self.environ = dict()

        self._newEnvVar('', '%')
        self._newEnvVar('DATE', envobj=_EnvDateObject())
        self._newEnvVar('TIME', envobj=_EnvTimeObject())

    def set(self, name, value, attr=None):
        self._updateEnvVar(name, value, attr)

    def get(self, name=None):
        if name:
            if name in self.environ:
                return self.environ[name]
            else:
                return None
        else:
            return self.environ

    def _newEnvVar(self, name, value=None, attr=None, envobj=None):
        if envobj:
            self.environ[name] = envobj
        else:
            self.environ[name] = _EnvObject(value, attr or 'str')

    def _updateEnvVar(self, name, value, attr=None):
        if name in self.environ:
            self.environ[name].setValue(value)
        else:
            self._newEnvVar(name, value, attr)

    def escape(self, line):
        firstp = line.find('%')
        while firstp > -1 and firstp + 1 < len(line):
            nextp = line.find('%', firstp + 1)
            if nextp != -1:
                variant = line[firstp + 1:nextp]
                if variant in self.environ:
                    val = str(self.environ[variant])
                    line = line.replace('%%%s%%' % variant, val)

                    nextp = firstp + len(val)

                firstp = line.find('%', nextp + 1)
            else:
                firstp = -1

        return line

    def unescape(self, line):
        ret = line
        envs = filter(lambda k: k not in ('DATE', 'TIME'), self.environ.keys())

        for k in envs:
            val = str(self.environ[variant])
            if ret.find(unicode(val)) > -1:
                ret = ret.replace(val, '%%%s%%' % k)

        return ret
